/** @file    Bus.cpp
 *  @author  Alessandro Polo
 *  @version $Id: Bus.cpp 2890 2010-08-12 01:57:23Z alex $
 *  @brief
 * File containing methods for the wosh::Bus class.
 * The header for this class can be found in Bus.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include <core/Bus.h>

 #include <core/BusManager.h>
 #include <core/ObjectFactory.h>
 #include <core/Utilities.h>
 #include <core/WoshKernel.h>
 #include <core/DataModels.h>


using namespace std;
namespace wosh {

 WOSH_REGISTER_INTERFACE(wosh::Bus, "wosh::Object", 1.01, _static_Bus)

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

Bus::Bus()
	: Object() {
	this->busID = Utilities::randomLong();
	this->busID = _GET_Abs(this->busID);
	this->sharedNetwork = true;
	this->sharedLocal = true;

	this->dutyCycleLast = 0.0;
	this->dutyCycleAverage = 0.0;
	this->dutyCycleCount = 0.0;

	setName( Utilities::format(_Bus_NAME"#%ld", this->busID ));

	Log.setContext( Object::getName() );
	Log.setIndent( 1 );
	Log.setLevel( LOG_INFO );
 }

Bus::~Bus() {
	// unlink listeners references
	this->nodes.transactionBeginWrite();
	this->nodes.getVector().clear();
	this->nodes.transactionEnd();
	push_event( Bus::STATE_DESTROYED );
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////// BUS EVENTS

void Bus::push_event( Bus::BUS_STATE state ) {
	BusManager::push_event( state, this );
 }

void Bus::push_message( const Message* message ) {
	BusManager::push_message( message, this );
 }

////////////////////////////////////////////////////////////////////////////////////////////////// BUS EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// HELPERS

void Bus::setName( const std::string& value ) {
	Object::setName(value);
	Log.setContext(value);
}

void Bus::assignSourceKernel( Message* message ) const {
	if ( message == NULL ) return;
	if ( !message->source.isKernelEmpty() )
		return;
	message->setSourceKernel( WoshKernel::getKernelName() );
 }

void Bus::assignBus( Message* message ) const {
	if ( message == NULL ) return;

	message->currentBus = Object::getName();

	if ( message->getSourceBus() == "" )
		message->sourceBus = Object::getName();

	if ( message->getDestinationBus() == "" )
		message->destinationBus = Object::getName();
 }

void Bus::assignID( Message* message, long id ) const {
	if ( message == NULL ) return;
	if ( id == 0 ) {
		message->id = Utilities::randomInt();
		message->id = _GET_Abs(message->id);
	 }
	else
		message->id = id;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void Bus::flushMessages() {
	Log(LOG_INFO, ":flushMessages() : Clearing queue.." );
	this->msgQueue.clear();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void Bus::postMessage( Message* message ) const {
	if ( message == NULL ) return;
	Bus::assignSourceKernel( message );
	Bus::assignBus( message );
	if ( message->getID() == 0 )
		Bus::assignID( message );
	if ( !message->hasSecurityToken() )
		Log(LOG_WARNING, ":postMessage(%"PRId64") Missing SecurityToken by [%s]", message->getID(), message->getSource().toString().c_str() );
	if ( !message->getSource().isValid() )
		Log(LOG_WARNING, ":postMessage(%"PRId64") Invalid Source URI [%s]", message->getID(), message->getSource().toString().c_str() );
	this->msgQueue.push_back( message );
	if ( !isBusRunning() )
		Log(LOG_WARNING, ":postMessage() : Message added to Stack but thread is not running." );
 }

///////////////////////////////////////////////////////////////////////////////////////////////////// HELPERS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////// HANDLERS

WRESULT Bus::addBusListener( IBusListener* node, bool deferred_add ) {
	if ( node == NULL ) return WRET_ERR_PARAM;
	if ( deferred_add ) {
		this->nodes_add.transactionBeginWrite();
		if ( this->nodes_add.exists(node) )
			Log(LOG_WARNING, ":addBusListener(%p) Listener already registered (in queue)!", node );
		else
			Log(LOG_VERBOSE, ":addBusListener(%p) Queued Listener registration", node );
		this->nodes_add.push_back(node);
		this->nodes_add.transactionEnd();
	 }
	else {
		this->nodes.transactionBeginWrite();
		if ( !this->nodes.exists(node) ) {
			this->nodes.push_back(node, true);
			Log(LOG_VERBOSE, ":addBusListener(%p) Listener registered", node );
		 }
		else
			Log(LOG_WARNING, ":addBusListener(%p) Listener already registered!", node );
		node->busEvent( Bus::STATE_STARTED, this);
		this->nodes.transactionEnd();
	 }
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

WRESULT Bus::removeBusListener( IBusListener* node, bool deferred_remove ) {
	if ( node == NULL ) return WRET_ERR_PARAM;
	if ( deferred_remove ) {
		this->nodes_remove.transactionBeginWrite();
		if ( this->nodes_remove.exists(node) )
			Log(LOG_WARNING, ":removeBusListener(%p) Listener already registered (in queue)!", node );
		else
			Log(LOG_VERBOSE, ":removeBusListener(%p) Queued Listener deregistration", node );
		this->nodes_remove.push_back(node);
		this->nodes_remove.transactionEnd();
	 }
	else {
		this->nodes.transactionBeginWrite();
		if ( !this->nodes.exists(node) ) {
			this->nodes.transactionEnd();
			Log(LOG_WARNING, ":removeBusListener(%p) Listener not found!", node );
			return WRET_ERR_ILLEGAL_USE;
		 }
		this->nodes.pop(node);
		Log(LOG_VERBOSE, ":removeBusListener(%p) Listener removed", node );
		this->nodes.transactionEnd();
	 }
	return WRET_OK;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void Bus::fixDeferredListeners() {
	tIBusListenerList::Iterator it;
	this->nodes.transactionBeginWrite();

	this->nodes_remove.transactionBeginWrite();
	for ( it=this->nodes_remove.begin(); it!=this->nodes_remove.end(); ++it ) {
		if ( *it == NULL ) continue;
		if ( !this->nodes.exists(*it) ) {
			Log(LOG_WARNING, ":fixDeferredListeners(%p) Listener not found!", *it );
			continue;
		 }
		this->nodes.pop(*it);
		Log(LOG_VERBOSE, ":fixDeferredListeners(%p) Listener unregistered", *it );
	 }
	this->nodes_remove.getVector().clear();
	this->nodes_remove.transactionEnd();

	this->nodes_add.transactionBeginWrite();
	for ( it=this->nodes_add.begin(); it!=this->nodes_add.end(); ++it ) {
		if ( *it == NULL ) continue;
		if ( this->nodes.exists(*it) ) {
			Log(LOG_WARNING, ":fixDeferredListeners(%p) Listener already registered!", *it );
			continue;
		 }
		this->nodes.push_back(*it);
		Log(LOG_VERBOSE, ":fixDeferredListeners(%p) Listener registered", *it );
	 }
	this->nodes_add.getVector().clear();
	this->nodes_add.transactionEnd();

	this->nodes.transactionEnd();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

bool Bus::isBusListener( const IBusListener* node ) const {
	if ( node == NULL ) return WRET_ERR_PARAM;
	MutexLockerRead mL(this->nodes.getMutex());
	return this->nodes.exists(node);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////// HANDLERS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

DataFieldCollector<Bus>* Bus::getDataFields() {
	DataFieldCollector<Bus>* fields = new DataFieldCollector<Bus>();
	fields->add<long, Variant>(&Bus::getBusID, "ID", 0);
	fields->add<const std::string&, Variant>(&Bus::getName, "Name", 1);
	fields->add<const char*, Variant>(&Bus::getClassName, "Type", 2);
	fields->add<bool,Variant>(&Bus::isBusRunning, "Running", 2);
	fields->add<bool,Variant>(&Bus::isSharedLocal, "LocS", 3);
	fields->add<bool,Variant>(&Bus::isSharedNetwork, "NetS", 4);
	fields->add<int,Variant>(&Bus::countBusListeners, "Handlers", 5, false);
	fields->add<int,Variant>(&Bus::getQueueSize, "QueueSize", 6, false);
	fields->add<double,Variant>(&Bus::getDutyCycleAverage, "DutyCycleAverage", 7, false);
	fields->add<double,Variant>(&Bus::getDutyCycleLast, "DutyCycleLast", 8, false);
	fields->add<const std::string&,Variant>(&Bus::getEntityID, "EntityID", 9, false);
	fields->add<const Permission&,Permission>(&Bus::getPermission, "Permission", 10, false);
	return fields;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////// STATS

double Bus::getDutyCycleAverage() const {
	MutexLockerRead mL(&this->statsMux);
	return this->dutyCycleAverage;
 }

double Bus::getDutyCycleLast() const {
	MutexLockerRead mL(&this->statsMux);
	return this->dutyCycleLast;
 }


void Bus::processingInitialize()
 {
	MutexLockerWrite mL(&this->statsMux);
	this->dutyCycleLast = 0.0;
	this->dutyCycleAverage = 0.0;
	this->dutyCycleCount = 0.0;
	this->dutyCycleTimer.start();
	this->dutyCycleTimer.stop();
 }

void Bus::processingStarted()
 {
	// previous processing time is saved in the Timer
	double processingTime = this->dutyCycleTimer.getTimeSpanMilliSec();
	// move the STOP timestampo to now, calculating total period
	this->dutyCycleTimer.stop();
	double period = this->dutyCycleTimer.getTimeSpanMilliSec();
	if ( period != 0 ) {
		this->dutyCycleLast = processingTime / period;
		this->dutyCycleAverage = (this->dutyCycleCount * this->dutyCycleAverage) + this->dutyCycleLast;
		this->dutyCycleAverage /= ++this->dutyCycleCount;
	}
	this->dutyCycleTimer.start();
 }

void Bus::processingFinished()
 {
	MutexLockerWrite mL(&this->statsMux);
	this->dutyCycleTimer.stop();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string BusDebugInfo_NULL = "NULL";

void BusDebugInfo::setCurrentMessage( const Message* message ) {
	transactionBeginWrite();
	if ( message == NULL )
		this->messageId = 0;
	else
		this->messageId = message->getID();
	transactionEnd();
}

void BusDebugInfo::setCurrentListener( IBusListener* listener ) {
	transactionBeginWrite();
	BusConnector* objConn = dynamic_cast<BusConnector*>(listener);
	if ( objConn == NULL || objConn->getMessageHandler() == NULL ) {
		Object* obj = dynamic_cast<Object*>( listener );
		if ( obj == NULL )
			this->currentListener = BusDebugInfo_NULL;
		else
			this->currentListener = obj->getName();
	 }
	else {
		Object* obj = dynamic_cast<Object*>( objConn->getMessageHandler() );
		if ( obj == NULL )
			this->currentListener = BusDebugInfo_NULL;
		else
			this->currentListener = obj->getName();
	}
	transactionEnd();
 }

std::string BusDebugInfo::getCurrentListener() const {
	MutexLockerRead mL(&this->mux);
	return this->currentListener;
 }
int64 BusDebugInfo::getMessageId() const {
	MutexLockerRead mL(&this->mux);
	return this->messageId;
 }

/////////////////////////////////////////////////////////////////////////////////////////////////////// STATS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

}; // namespace wosh
